﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Wasion.HHU.Common;
using Wasion.HHU.Services;
using Windows.ApplicationModel;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Rfcomm;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation.Peers;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using WsProtocol.IEC62056;
using WsProtocol.IEC62056MDL;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Wasion.HHU.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Meter : Page
    {

        public Meter()
        {
            this.InitializeComponent();
            App.Current.Suspending += App_Suspending;
            NavigationCacheMode = NavigationCacheMode.Enabled;

            Shell.Meter.showInfo += Meter_showInfo;
            Shell.Meter.ConnCompleted += Meter_ConnCompleted;

            var _enumval1 = Enum.GetValues(typeof(SecurityPolicy)).Cast<SecurityPolicy>();
            SecunityPlicy.ItemsSource = _enumval1.ToList();
            SecunityPlicy.SelectedItem = SecurityPolicy.需认证加密;

            var _enumval2 = Enum.GetValues(typeof(AuthenticationExpand)).Cast<AuthenticationExpand>();
            AuthMechanism.ItemsSource = _enumval2.ToList();
            AuthMechanism.SelectedItem = AuthenticationExpand.HLS_GMAC;

            var _enumval3 = Enum.GetValues(typeof(RequirContext)).Cast<RequirContext>();
            AppContextName.ItemsSource = _enumval3.ToList();
            AppContextName.SelectedItem = RequirContext.LN_Cipher;

            MeterNumber.Text = "SIE1051911000084";
            MeterAddress.Text = "16";
            PassWord.Text = "33333333,33333333,33333333";
            ClientAddr.Text = "01";
        }

        

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            
            DataContext = this;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            
        }

        private void App_Suspending(object sender, SuspendingEventArgs e)
        {
            
        }


        private async void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            var am = (AuthenticationExpand)AuthMechanism.SelectedItem;
            var ac = (RequirContext)AppContextName.SelectedItem;
            var sp = (SecurityPolicy)SecunityPlicy.SelectedItem;
            var meterNumber = MeterNumber.Text.Trim();
            int meterAddress = 16;
            if (!int.TryParse(MeterAddress.Text.Trim(), out meterAddress))
            {
                return;
            }
            var pw = PassWord.Text.Trim();
            var clientAddr = ClientAddr.Text.Trim();

            //Shell.Meter = Shell.MeterManager.CreateMeter();

            var testMeter = new TestMeter(Shell.Meter);
            testMeter.MeterNO = meterNumber;//"SIE1051911000084";
            testMeter.MeterName = "Meter2-HLS_GMAC";
            testMeter.MeterCommAddr = meterAddress.ToString();//"16";
            testMeter.Meter62056.MeterCommAddr = meterAddress;//16;
            testMeter.Meter62056.PassWord = pw;//"33333333,33333333,33333333";
            testMeter.Meter62056.SecurityModeExpand = am;//WsProtocol.IEC62056MDL.AuthenticationExpand.HLS_GMAC;
            testMeter.Meter62056.EncParams.securityPolicy = sp;//SecurityPolicy.需认证加密;
            testMeter.Meter62056.ContextName = ac;
            testMeter.Meter62056.ProConform = "FFFFFF";
            testMeter.Meter62056.SendMaxSize = "1280";
            testMeter.Meter62056.RecMaxSize = "1280";
            testMeter.Meter62056.RecMaxWindow = "7";
            testMeter.Meter62056.APDUSize = "1277";
            testMeter.CommInfo.CommName = "";
            testMeter.CommInfo.Port = 0;
            testMeter.CommInfo.SNO = 1;
            testMeter.CommInfo.ConnMode = SourceMeterMode.串口485;
            testMeter.ConnectMode = "1";
            testMeter.FCurrent = "1.5(6)";
            testMeter.MeterID = "2";//表位
            testMeter.SNO = 2;//表ID 数据库中主键
            testMeter.Voltage = "220";
            testMeter.checkState = WsProtocol.PublicClass.CheckState.Unchecked;
            testMeter.PassWord = pw;//"33333333,33333333,33333333";

            //var CAddr = "01";
            testMeter.Meter62056.MTRole = TMeterTypeRole.GetRoleByCAddr(clientAddr, PtlConsts.roleLst);
            Shell.Meter.MeterLst.Clear();
            Shell.Meter.MeterLst.Add(testMeter);

            
            Shell.Meter.ConnectAsync();
            ConnectButton.IsEnabled = false;
            DisconnectButton.IsEnabled = false;
        }

        private void Meter_ConnCompleted(object sender, ViewModels.MsgInfoEventArgs e)
        {
            string msg = "";
            if (e.Code == "0")
            {
                msg = "连接电表成功 "+Environment.NewLine;
                ConnectButton.IsEnabled = false;
                DisconnectButton.IsEnabled = true;
            }
            else if(e.Code == "-1")
            {
                msg = "连接电表失败 " + Environment.NewLine;
                ConnectButton.IsEnabled = true;
                DisconnectButton.IsEnabled = false;
            }
            else if (e.Code == "-2")
            {
                msg = "已断开链接 " + Environment.NewLine;
                ConnectButton.IsEnabled = true;
                DisconnectButton.IsEnabled = false;
            }
            msg += e.Msg;
            NotifyUser(msg, NotifyType.StatusMessage);
        }

        private void Meter_showInfo(object sender, ViewModels.MsgInfoEventArgs e)
        {
            NotifyUser(e.Msg, NotifyType.StatusMessage);
        }

        private void DisconnectButton_Click(object sender, RoutedEventArgs e)
        {
            //var item = (SecurityPolicy)SecunityPlicy.SelectedItem;
            //var s =item.ToString();

            ConnectButton.IsEnabled = false;
            DisconnectButton.IsEnabled = false;
            Shell.Meter.DisConnectAsync();
        }


        private void ResetMainUI()
        {
            
        }

        /// <summary>
        /// Display a message to the user.
        /// This method may be called from any thread.
        /// </summary>
        /// <param name="strMessage"></param>
        /// <param name="type"></param>
        public void NotifyUser(string strMessage, NotifyType type)
        {
            // If called from the UI thread, then update immediately.
            // Otherwise, schedule a task on the UI thread to perform the update.
            if (Dispatcher.HasThreadAccess)
            {
                UpdateStatus(strMessage, type);
            }
            else
            {
                var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateStatus(strMessage, type));
            }
        }
        private void UpdateStatus(string strMessage, NotifyType type)
        {
            switch (type)
            {
                case NotifyType.StatusMessage:
                    StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
                    break;
                case NotifyType.ErrorMessage:
                    StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
                    break;
            }

            StatusBlock.Text += strMessage;

            // Collapse the StatusBlock if it has no text to conserve real estate.
            StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed;
            if (StatusBlock.Text != String.Empty)
            {
                StatusBorder.Visibility = Visibility.Visible;
                StatusPanel.Visibility = Visibility.Visible;
            }
            else
            {
                StatusBorder.Visibility = Visibility.Collapsed;
                StatusPanel.Visibility = Visibility.Collapsed;
            }

            // Raise an event if necessary to enable a screen reader to announce the status update.
            var peer = FrameworkElementAutomationPeer.FromElement(StatusBlock);
            if (peer != null)
            {
                peer.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
            }
        }

        private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdatePairingButtons();
        }

        private void UpdatePairingButtons()
        {
            
        }

        private void StatusPanel_Tapped(object sender, TappedRoutedEventArgs e)
        {
            StatusPanel.Height = 300;
            StatusScrollViewer.MaxHeight = 300;
            StatusScrollViewer.Height = 300;
            //DisplayNoWifiDialog();
            e.Handled = true;
        }

        private async void DisplayNoWifiDialog()
        {
            ContentDialog noWifiDialog = new ContentDialog()
            {
                Title = "No wifi connection",
                Content = "Check connection and try again.",
                CloseButtonText = "Ok"
            };

            await noWifiDialog.ShowAsync();
        }

        private void Page_Tapped(object sender, TappedRoutedEventArgs e)
        {
            StatusPanel.Height = 50;
            StatusScrollViewer.MaxHeight = 50;
            StatusScrollViewer.Height = 50;
        }
    }
}
